package com.spark.laboratory.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Random;


public class TestJWT {

    String uri = "http://202.205.145.156:8017/project/log/upload";

    @Test
    public void test3(){
        System.out.println(getRandomString2());
    }
    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(){
        StringBuilder sb =new StringBuilder();
        for(int i = 0 ;i < 16;i ++){
            if (i % 2 == 0) {
                char[] cha ={'A','B','C','D','E','F'};
                int i1 = (int) (Math.random() * (cha.length));
                sb.append(cha[i1]);
            }else {
                sb.append(new Random().nextInt(10));
            }
        }
        return sb.toString();
    }
    public static String urlEncodeURL(String url) {
        try {
            String result = URLEncoder.encode(url, "UTF-8");
            result = result.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");//+实际上是 空格 url encode而来
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void test2() throws Exception {
        String dencrty = dencrty("");
        System.out.println(dencrty);
    }

    @Test
    public void test1() {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                uri += "AAABc8huPXUCAAAAAAABkcM%3D.5wjhcb9FBCSurZVQC9bImdJb3LeKWVkjvxf%2FJZ8ZzNmQUxLjBpv3Q9P5RCVyS4Q4RzXNc%2FH0%2B8FzLOknXBatFolLpCesRn8SLrzIfbfVALrcru6%2BOByBeDFiWLvmm6xFN06qrcdmayLafjKU9SZ%2BT7IYRzJ2nstr%2F0GIIlf1VUB%2FMg2Py6bOxEhypH81v2tn8HkQPAdhw%2FuSWBp6WQWRVg%3D%3D.o1N2jmUr22tSZvBuNEgBfTe6%2BoVqpSahAFiyteWFh1s%3D";

                HttpGet httpGet = new HttpGet(urlEncodeURL(uri));

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                org.apache.http.HttpEntity entity1 = response.getEntity();
                String result = EntityUtils.toString(entity1);

                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        try
        {
            String data= "";
//            // =================示例：解密xjwt (token也是一个xjwt);
//            String xjwt = "AAABc8hMB9oCAAAAAAAPQj8%3D.p%2FN4y4MpmtFgz4NM9OouTxVNUKllZasXY73xNsNnYlDzdD6lGCcEMfpeSg7QxtqO.cFlIucLERUxuVSV%2FSrM2GQGpuEYA0BWTjf6qQvUwtbw%3D";
//            data = dencrty(xjwt);
//            System.out.println(data);

            // =================示例：生成xjwt
            JSONObject param=new JSONObject();
            param.put("username","13317962585");
            param.put("projectTitle","特种铸造虚拟仿真实验");
            param.put("score",100);
            param.put("startDate", System.currentTimeMillis());
            param.put("endDate", System.currentTimeMillis() + 30000);
            param.put("timeUsed", 3);
            param.put("issuerId", "102851");

            System.out.println("System.currentTimeMillis() = " + System.currentTimeMillis());

            String json=param.toString();

            data = encrty(json);
            System.out.println(data);

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static String dencrty(String xjwt) throws Exception {
        //获取当前时间
        long now = System.currentTimeMillis();
        //创建JWT实例
        JWT jwt = new JWT(KEY.secret, KEY.aeskey,now, KEY.issueId);
        //对数据进行url 解码
        xjwt=URLDecoder.decode(xjwt,"UTF-8");
        //解密数据
        String json = jwt.verifyAndDecrypt(xjwt,now);
        return json;
    }
    public static String encrty(String json) throws Exception {
        //获取当前时间
        long now=System.currentTimeMillis();
        //创建JWT实例
        JWT jwt=new JWT(KEY.secret, KEY.aeskey,now, KEY.issueId);
        //创建payload
        ByteBuffer payload = ByteBuffer.allocate(1024).order(ByteOrder.BIG_ENDIAN);
        payload.put(json.getBytes("UTF-8")).flip();
        //创建out
        ByteBuffer out = ByteBuffer.allocate(1024);
        //加密数据
        jwt.encryptAndSign(JWT.Type.SYS,payload,out,now+10*60*1000); //设置过期时间，例:10分钟
        String xjwt = new String(out.array(),out.arrayOffset(),out.remaining());
        //对数据进行url 编码
        return URLEncoder.encode(xjwt,"UTF-8");
    }
}
